<template>
  <PictureComponent pictureHeight="60px" :picUrl="picUrl" style="margin-bottom: 5px" :noPicUrl="noPhotoSrc" />
  <el-link type="primary" icon="Picture" @click="photoSelectDialog.openDialog()">选择图片</el-link>
  <el-input v-model="fileResourceId" readonly v-show="showInput" />
  <!--图片选择对话框-->
  <PhotoSelectDialog ref="photoSelectDialog" @afterSubmit="afterSelectPhoto" />
</template>

<script lang="ts" setup>
// 导入上传图像组件
import PhotoSelectDialog from '@/components/base/dialog/PhotoSelectDialogComponent.vue';
import PictureComponent from '@/components/base/other/PictureComponent.vue';

import { computed, nextTick, provide, ref, watch } from 'vue';
import { defineEmits } from 'vue';
import type { FormHeader, ResponseData } from '@/types/interface/base_interface';
import { ElMessage } from 'element-plus';
import urls from '@/api/request/urls';
import Request from '@/api/request/request';
import { noPhotoSrc } from '@/api/pic';

const emit = defineEmits(['uploadSuccess']);

//绑定input
const fileResourceId = defineModel<string>({
  required: false,
  default: ''
});
//获取图片地址
const picUrl = ref<string>('');

// 接收父组件的值
interface Props {
  //图片上传对话框组件的属性
  dialogWidth?: string; // 对话框宽度
  dialogTitle?: string; // 对话框标题,前台传入，不用加入添加或编辑的文本。添加或编辑的文本由action属性决定
  showDialogFoot?: Boolean; // 是否显示对话框脚部
  multiple?: Boolean; // 是否多选。默认不多选
  multipleLimit?: number; //multiple 属性设置为 true 时，代表多选场景下用户最多可以选择的项目数， 为 0 则不限制
  limit?: number; // 允许选择的最大数量
  autoUpload?: boolean; // 是否自动上传
  data?: Record<string, any>; // 上传时附带的额外参数
  showInput?: boolean; //是否显示文本框
}
const props = withDefaults(defineProps<Props>(), {
  multiple: () => Boolean(false),
  multipleLimit: 1,
  autoUpload: true,
  showInput: false
});
//根据图片id加载图片
const loadPhoto = async (fileResourceIdOfSelect: string) => {
  //加载资源对应的图片信息
  const resData: ResponseData = await new Request(`${urls.API_URL_BACKSTAGE_FILERESOURCE_MANAGE}/${fileResourceIdOfSelect}`).get();
  if (resData.success) {
    picUrl.value = resData.data.fileHttpUrl;
  }
};
//图片选择对话框
const photoSelectDialog = ref();
//在选择了图片之后
const afterSelectPhoto = async (checkSelect: Array<string>) => {
  fileResourceId.value = checkSelect[0];
  //加载资源对应的图片信息。后改为通过watch监听来进行加载
  // await loadPhoto(checkSelect[0]);
};
//监听资源的Id
watch(
  () => {
    return fileResourceId.value;
  },
  async (newValue, oldValue) => {
    if (typeof newValue !== 'undefined' && newValue != null && newValue.length > 0) {
      //如果资源不为空，加载资源对应的图片信息
      await loadPhoto(newValue);
    } else {
      //如果资源为空，让图片信息为null
      picUrl.value = '';
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.photo-upload-dialog {
  .el-upload__tip {
    text-align: center;
  }
}
div.picture_name {
  overflow: hidden; /* 隐藏超出部分的文本 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  white-space: nowrap; /* 文本不换行 */
  text-align: center;
}
</style>
